<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { queryGoodsDetail } from '@/services/goods'
import { postMemberCartApi } from '@/services/cart'
import type { LocationItem } from '@/types/address'
import type { GoodsResult } from '@/types/goods'
import type {
  SkuPopupLocaldata,
  SkuPopupInstanceType,
} from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import { queryAddressList } from '@/services/address'
import ServicePanel from '@/pages/goods/components/ServicePanel.vue'
import AddressPanel from '@/pages/goods/components/AddressPanel.vue'
import { useAddress } from '@/stores/modules/address'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取参数
const query = defineProps<{
  id: string
}>()

// 获取商品详情数据
const goods = ref<GoodsResult>()
const getGoodsDetailData = async () => {
  const res = await queryGoodsDetail(query.id)
  goods.value = res.result

  // sku组件所需localdata数据
  localData.value = {
    /** 商品 ID */
    _id: res.result.id,
    /** 商品名称 */
    name: res.result.name,
    /** 商品图片 */
    goods_thumb: res.result.mainPictures[0],
    /** 商品规格列表 */
    spec_list: res.result.specs.map((spec) => {
      return {
        name: spec.name,
        list: spec.values,
      }
    }),
    /** 商品SKU列表 */
    sku_list: res.result.skus.map((sku) => {
      return {
        /** SKU ID */
        _id: sku.id,
        /**  商品 ID */
        goods_id: res.result.id,
        /** 商品名称 */
        goods_name: res.result.name,
        /** 商品图片 */
        image: sku.picture,
        /** SKU 价格 * 100, 注意：需要乘以 100 */
        price: sku.price * 100,
        /** SKU 规格组成, 注意：需要与 spec_list 数组顺序对应 */
        sku_name_arr: sku.specs.map((spec) => spec.valueName),
        /** SKU 库存 */
        stock: sku.inventory,
      }
    }),
  }
}

// 获取收货地址列表数据
const addressList = ref<LocationItem[]>()
const getAddressList = async () => {
  const res = await queryAddressList()
  addressList.value = res.result
}

// 计算选中的收货地址
const addressStore = useAddress()
const selectedAddress = computed(() => {
  if (addressStore.selectedAddress) {
    return addressStore.selectedAddress
  } else {
    return addressList.value?.find((address) => address.isDefault)
  }
})

// 页面加载的时候执行
onShow(() => {
  getGoodsDetailData()
  getAddressList()
  console.log(selectedAddress, 'selectedAddress')
})

// 轮播图变化时绑定事件
const curBannerIndex = ref(0)
const handleBannerChange: UniHelper.SwiperOnChange = (event) => {
  curBannerIndex.value = event.detail!.current
}

// 点击轮播图的图片的时候
const handleTapImage = (url: string) => {
  // 大图预览
  uni.previewImage({
    current: url,
    urls: goods.value!.mainPictures,
  })
}

// 弹出层ref实例
const popup = ref<{
  open: (
    type?: 'top' | 'center' | 'bottom' | 'left' | 'right' | 'message' | 'dialog' | 'share',
  ) => void
  close: () => void
}>()

// 弹出框选项
const popupName = ref<'service' | 'address'>()

// 弹出层操作
const openPopup = (type: typeof popupName.value) => {
  popupName.value = type
  popup.value?.open()
}

// 是否展示 SKU
const isShowSku = ref(false)

// 后端返回商品信息
const localData = ref({} as SkuPopupLocaldata)

// sku模式 1:都显示 2:只显示购物车 3:只显示立即购买
// 枚举类型
enum SkuMode {
  Both = 1,
  Cart = 2,
  Buy = 3,
}
const skuMode = ref<SkuMode>(SkuMode.Both)

// 显示SKU
const showSku = (mode: SkuMode) => {
  skuMode.value = mode
  isShowSku.value = true
}

// 获取SKU组件实例
const skuInstance = ref<SkuPopupInstanceType>()

// 计算商品详情页面 选择栏显示数据
const selectedArrText = computed(() => {
  return skuInstance.value?.selectArr?.join(' ').trim() || '请选择商品规格'
})

// 加入购物车中的已勾选的数据类型
type selectShop = {
  buy_num: number
  goods_id: string
  goods_name: string
  image: string
  price: number
  sku_name_arr: Array<string>
  stock: number
  _id: string
}
// 加入购物车事件
const onAddCart = async (event: selectShop) => {
  await postMemberCartApi({ skuId: event._id, count: event.buy_num })
  uni.showToast({
    title: '添加成功',
    icon: 'success',
  })
  isShowSku.value = false
}

// 立即购买
const onBuyNow = async (event: selectShop) => {
  const skuId = event._id
  const count = event.buy_num
  const addressId = selectedAddress.value?.id
  uni.navigateTo({
    url: `/pagesOrder/create/create?skuId=${skuId}&count=${count}&addressId=${addressId}`,
  })
}
</script>

<template>
  <vk-data-goods-sku-popup
    ref="skuInstance"
    v-model="isShowSku"
    :localdata="localData"
    :mode="skuMode"
    add-cart-background-color="#ffa868"
    buy-now-background-color="#27ba9b"
    :actived-style="{
      color: '#27ba9b',
      borderColor: '#27ba9b',
      backgroundColor: '#e9f8f5',
    }"
    @add-cart="onAddCart"
    @buy-now="onBuyNow"
  ></vk-data-goods-sku-popup>
  <scroll-view scroll-y class="viewport">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper circular @change="handleBannerChange">
          <swiper-item v-for="(img, index) in goods?.mainPictures" :key="index">
            <image @tap="handleTapImage(img)" mode="aspectFill" :src="img" />
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text class="current">{{ curBannerIndex + 1 }}</text>
          <text class="split">/</text>
          <text class="total">{{ goods?.mainPictures.length }}</text>
        </view>
      </view>

      <!-- 商品简介  -->
      <view class="meta">
        <view class="price">
          <text class="symbol">¥</text>
          <text class="number">{{ goods?.price }}</text>
        </view>
        <view class="name ellipsis"> {{ goods?.name }} </view>
        <view class="desc"> {{ goods?.desc }} </view>
      </view>

      <!-- 操作面板 -->
      <view class="action">
        <view @tap="showSku(SkuMode.Both)" class="item arrow">
          <text class="label">选择</text>
          <text class="text ellipsis"> {{ selectedArrText }} </text>
        </view>
        <view @tap="openPopup('address')" class="item arrow">
          <text class="label">送至</text>
          <text class="text ellipsis">
            {{
              selectedAddress
                ? `${selectedAddress.fullLocation} ${selectedAddress.address}`
                : '请选择收获地址'
            }}
          </text>
        </view>
        <view @tap="openPopup('service')" class="item arrow">
          <text class="label">服务</text>
          <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail panel">
      <view class="title">
        <text>详情</text>
      </view>
      <view class="content">
        <view class="properties">
          <!-- 属性详情 -->
          <view class="item" v-for="detail in goods?.details.properties" :key="detail.value">
            <text class="label">{{ detail.name }}</text>
            <text class="value">{{ detail.value }}</text>
          </view>
        </view>
        <!-- 图片详情 -->
        <image
          v-for="detailImg in goods?.details.pictures"
          :key="detailImg"
          mode="widthFix"
          :src="detailImg"
        ></image>
      </view>
    </view>

    <!-- 同类推荐 -->
    <view class="similar panel">
      <view class="title">
        <text>同类推荐</text>
      </view>
      <view class="content">
        <navigator
          v-for="item in goods?.similarProducts"
          :key="item.id"
          class="goods"
          hover-class="none"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          <image class="image" mode="aspectFill" :src="item.picture"></image>
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ item.price }}</text>
          </view>
        </navigator>
      </view>
    </view>
  </scroll-view>

  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="icons">
      <button class="icons-button"><text class="icon-heart"></text>收藏</button>
      <button class="icons-button" open-type="contact">
        <text class="icon-handset"></text>客服
      </button>
      <!-- open-type="switchTab" tabBar页面跳转之后无法返回上个页面； open-type="navigate" 可以 -->
      <navigator class="icons-button" url="/pages/cart/cart2" open-type="navigate">
        <text class="icon-cart"></text>购物车
      </navigator>
    </view>
    <view class="buttons">
      <view class="addcart" @tap="showSku(SkuMode.Cart)"> 加入购物车 </view>
      <view class="buynow" @tap="showSku(SkuMode.Buy)"> 立即购买 </view>
    </view>
  </view>

  <!-- 弹出层 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <AddressPanel
      :list="addressList!"
      :selectedAddress="selectedAddress!"
      v-if="popupName === 'address'"
      @close="popup?.close()"
    />
    <ServicePanel v-if="popupName === 'service'" @close="popup?.close()" />
  </uni-popup>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.viewport {
  background-color: #f4f4f4;
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;
    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #27ba9b;
    }
    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: '\e6c2';
    color: #ccc;
    font-family: 'erabbit' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

/* 商品信息 */
.goods {
  background-color: #fff;
  .preview {
    height: 750rpx;
    position: relative;
    .image {
      width: 750rpx;
      height: 750rpx;
    }
    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;
      .current {
        font-size: 26rpx;
      }
      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }
      .total {
        font-size: 24rpx;
      }
    }
  }
  .meta {
    position: relative;
    border-bottom: 1rpx solid #eaeaea;
    .price {
      height: 130rpx;
      padding: 25rpx 30rpx 0;
      color: #fff;
      font-size: 34rpx;
      box-sizing: border-box;
      background-color: #35c8a9;
    }
    .number {
      font-size: 56rpx;
    }
    .brand {
      width: 160rpx;
      height: 80rpx;
      overflow: hidden;
      position: absolute;
      top: 26rpx;
      right: 30rpx;
    }
    .name {
      max-height: 88rpx;
      line-height: 1.4;
      margin: 20rpx;
      font-size: 32rpx;
      color: #333;
    }
    .desc {
      line-height: 1;
      padding: 0 20rpx 30rpx;
      font-size: 24rpx;
      color: #cf4444;
    }
  }
  .action {
    padding-left: 20rpx;
    .item {
      height: 90rpx;
      padding-right: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      font-size: 26rpx;
      color: #333;
      position: relative;
      display: flex;
      align-items: center;
      &:last-child {
        border-bottom: 0 none;
      }
    }
    .label {
      width: 60rpx;
      color: #898b94;
      margin: 0 16rpx 0 10rpx;
    }
    .text {
      flex: 1;
      -webkit-line-clamp: 1;
    }
  }
}

/* 商品详情 */
.detail {
  padding-left: 20rpx;
  .content {
    margin-left: -20rpx;
    .image {
      width: 100%;
    }
  }
  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;
    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx;
      font-size: 26rpx;
      color: #333;
      border-bottom: 1rpx dashed #ccc;
    }
    .label {
      width: 200rpx;
    }
    .value {
      flex: 1;
    }
  }
}

/* 同类推荐 */
.similar {
  .content {
    padding: 0 20rpx 200rpx;
    background-color: #f4f4f4;
    display: flex;
    flex-wrap: wrap;
    .goods {
      width: 340rpx;
      padding: 24rpx 20rpx 20rpx;
      margin: 20rpx 7rpx;
      border-radius: 10rpx;
      background-color: #fff;
    }
    .image {
      width: 300rpx;
      height: 260rpx;
    }
    .name {
      height: 80rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #262626;
    }
    .price {
      line-height: 1;
      font-size: 20rpx;
      color: #cf4444;
    }
    .number {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }
  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ffa868;
    }
    .buynow,
    .payment {
      background-color: #27ba9b;
      margin-left: 20rpx;
    }
  }
  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
      &::after {
        border: none;
      }
    }
    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
</style>
